package colibridb.util;

import colibridb.util.*;

/**
 * 
 * @author Torsten Jaeger
 *
 */
public class SQLParser {

	String sqlStatement = null;
	
	boolean isSELECT = false;
	boolean isINSERT = false;
	boolean isUPDATE = false;
	boolean isCREATE = false;
	boolean isDROP = false;

	String[] columns = null;
	String tableName = null;
	
	String[] sqlParts = null;
	
	public SQLParser(String sqlStatement) {

		if (NameConventions.isValidSQLStatement(sqlStatement) == true) 
		{
			this.sqlStatement = sqlStatement;

			// separate by white spaces except a comma stands bevor
			sqlParts = sqlStatement.split("(?<!,)\\s");

			if (sqlParts != null) {
				// determine the sql operation
				isSELECT = sqlParts[0].toUpperCase().compareTo("SELECT") == 0 ? true: false; 
				isINSERT = sqlParts[0].toUpperCase().compareTo("INSERT") == 0 ? true: false;
				isUPDATE = sqlParts[0].toUpperCase().compareTo("UPDATE") == 0 ? true: false;
				isCREATE = sqlParts[0].toUpperCase().compareTo("CREATE") == 0 ? true: false;
				isDROP = sqlParts[0].toUpperCase().compareTo("DROP") == 0 ? true: false;
			}

			// find the columns
			findColumns();

			// find the table name
			findTableName();
		}
		
	}
		
	/**
	 * 
	 */
	private void findTableName() {
		
		String searchString = null;
		
		if (isSELECT) {
			searchString = "FROM"; // find the tablename after "FROM"
		}
		if (isINSERT) {
			searchString = "INTO"; // find the tablename after "INTO"
		}
		
		int i = 0;
		for (String sql_part : sqlParts) {
			if (sql_part.toUpperCase().compareTo(searchString) == 0) {
				tableName = sqlParts[++i];
				break;
			}
			i++;
		}
			
	}
	
	private void findColumns() {
		
		if (isSELECT) {
			// separate by comma and eliminate white spaces bevor and after
			columns = sqlParts[1].split("[\\s]?,[\\s]?");
		}
		if (isINSERT) {
			// TODO: Horia implementieren
//			String[] colTemp = sqlParts[3].split(",");
			if(sqlParts[3].startsWith("(") == true && 
					sqlParts[3].endsWith("") == true) {
				columns = sqlParts[3].substring(1, sqlParts[3].length()-1).split("[\\s]?,[\\s]?");
			} else {
				columns = null;
			}
		}
		
	}
	
	/**
	 * 
	 * @return
	 */
	public String[] getColumns() {
		return columns;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getTableName() {
		return tableName;
	}
}
